import axios from 'axios'

// 相关配置请参考：www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig = {
  baseURL: 'http://xxxx/',
  // 请求超时时间
  timeout: 10000,
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  },
  // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
  paramsSerializer: {
    // serialize: stringify as unknown as CustomParamsSerializer
  }
}

class kunRequest {
  constructor() {
    /** 保存当前Axios实例对象 */
    this.axiosInstance = axios.create(defaultConfig)
    /** 初始化配置对象 */
    this.initConfig = {}
    this.httpInterceptorsRequest()
    this.httpInterceptorsResponse()
  }

  httpInterceptorsRequest() {
    MusicRequest.axiosInstance.interceptors.request.use(
      async (config) => {
        // 优先判断post/get等方法是否传入回掉，否则执行初始化设置等回掉
        if (typeof config.beforeRequestCallback === 'function') {
          config.beforeRequestCallback(config)
          return config
        }
        if (MusicRequest.initConfig.beforeRequestCallback) {
          MusicRequest.initConfig.beforeRequestCallback(config)
          return config
        }
        // 接口设置时间戳
        config.params = {
          ...config.params,
          cookie: useCommonStoreHook().cookie ?? '',
          timestamp: Date.now()
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  }

  httpInterceptorsResponse() {
    const instance = MusicRequest.axiosInstance
    instance.interceptors.response.use(
      (response) => {
        const $config = response.config
        if (typeof $config.beforeResponseCallback === 'function') {
          $config.beforeResponseCallback(response)
          return response.data
        }
        if (MusicRequest.initConfig.beforeResponseCallback) {
          MusicRequest.initConfig.beforeResponseCallback(response)
          return response.data
        }
        return response.data
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  }

  static request(
    method,
    url,
    param,
    axiosConfig
  ) {
    const config = {
      method,
      url,
      ...param,
      ...axiosConfig
    }
    return new Promise((resolve, reject) => {
      MusicRequest.axiosInstance
        .request(config)
        .then((response) => {
          resolve(response)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  static get(
    url,
    param,
    config
  ){
    return this.request('get', url, param, config)
  }

  static post(
    url,
    param,
    config
  ){
    return this.request('post', url, param, config)
  }
}

export default new kunRequest()
